//
//  OrderRealtimeDataViewController.m
//  OMS
//
//  Created by goldeney on 14/10/22.
//  Copyright (c) 2014年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "OMOrderProjectDataViewController.h"
#import "NSKeyedArchiverUserLogin.h"
#import "NSDictionary+DataFormat.h"

#import "UITableView+Custom.h"
#import "WebServiceCommonRequest.h"
#import "MJRefresh.h"
#import "NSString+handle.h"

#import "OMOrderProjectDataViewCell.h"

@interface OMOrderProjectDataViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (strong, nonatomic) NSMutableArray *contentListData;
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) NSDictionary *concreteInfo;

@end

@implementation OMOrderProjectDataViewController
@synthesize tableView = _tableView;

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"请选择工程";
    }
    return self;
}

- (id)initWithConcreteInfo:(id)object
{
    self = [super init];
    if (self) {
        self.concreteInfo = object;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.contentListData = [NSMutableArray array];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, SuperHeight)];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.tableView.autoresizesSubviews = YES;
    [self.view addSubview:_tableView];
    
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 76;
    
    //获取合同数据
    [self setupRefresh];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)setupRefresh
{
    //添加下拉加载数据
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.tableView headerBeginRefreshing];
}

- (void)stopRefresh
{
    //移除下拉加载数据
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
}

- (void)cancel:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark 网络获取数据

- (void)getNetWorkData
{
    //@状态（全部、供毕、正供、待供）
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"HTGL_GCMC_LIST"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    NSString *concreteID = [self.concreteInfo objectFormatStringForKey:@"合同ID"];
    [content addParameterKey:@"合同ID" value:concreteID];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        [self stopRefresh];
        
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        [self.contentListData removeAllObjects];
        if(firstArray && firstArray.count>0){
            [self.contentListData addObjectsFromArray:firstArray];
            [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
            [self.tableView reloadData];
        } else{
            [self.tableView setTableViewNotDataDrawText:@"暂无工程" isShow:YES];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self errorInfoViewText:@"哦，出错了"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self errorInfoViewText:@"无法连接网络"];
    }];
    
}

- (void)errorInfoViewText:(NSString*)label
{
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
    
    if (self.tableView.visibleCells.count <= 0) {
        [self.tableView setTableViewNotDataDrawText:label isShow:YES];
    } else {
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        [self showErrorHUDText:label];
    }
}

#pragma mark 开始进入刷新状态

- (void)headerRereshing
{
    [self getNetWorkData];
}


#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.contentListData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellWithIdentifier = @"OMOrderProjectDataViewCell";
    OMOrderProjectDataViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellWithIdentifier];
    if (!cell) {
        cell = [[OMOrderProjectDataViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellWithIdentifier];
    }
    
    NSDictionary *dictionary = [self.contentListData objectAtIndex:indexPath.row];
    cell.GCMCLabel.text = [dictionary objectFormatStringForKey:@"工程名称" defaults:@"无工程名称"];
    cell.GCDZLabel.text = [dictionary objectFormatStringForKey:@"工地地址" defaults:@"未录入"];
    cell.SGDWLabel.text = [dictionary objectFormatStringForKey:@"施工单位" defaults:@"未录入"];
    cell.JSDWLabel.text = [dictionary objectFormatStringForKey:@"建设单位" defaults:@"未录入"];
    
    return cell;
}

#pragma mark - UITableViewDelegate
//
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    NSDictionary *dictionary = [self.contentListData objectAtIndex:indexPath.row];
//    NSString *groupSignature = [dictionary objectFormatStringForKey:@"施工单位" defaults:@"未录入"];
//    
//    static NSString *CellWithIdentifier = @"OMOrderProjectDataViewCell";
//    OMOrderProjectDataViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellWithIdentifier];
//    if (!cell) {
//        cell = [[OMOrderProjectDataViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellWithIdentifier];
//    }
//    
//    NSAttributedString *attStr = [[NSAttributedString alloc]initWithString:groupSignature];
//    NSRange range = NSMakeRange(0,attStr.length );
//    NSDictionary *dic = [attStr attributesAtIndex:0 effectiveRange:&range];
//    //计算实际frame大小，并将label的frame变成实际大小
//    CGSize size = [groupSignature boundingRectWithSize:cell.bounds.size options:NSStringDrawingUsesFontLeading attributes:dic context:nil].size;
//    CGRect frame = cell.textLabel.frame;
//    [cell.textLabel setFrame:CGRectMake(frame.origin.x,frame.origin.y, size.width, size.height)];
//
//    return 76;
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dictionary = [self.contentListData objectAtIndex:indexPath.row];
    
    //关闭页面，返回数据
    if (self.backResultDelagate && [self.backResultDelagate respondsToSelector:@selector(backResultDataKey:dataValue:)]) {
        [self.backResultDelagate backResultDataKey:self.key dataValue:dictionary];
        [self cancel:nil];
    }
}

#pragma mark - UIAlertView

- (void)showAlertView:(NSString*)message
{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    alert.alertViewStyle=UIAlertViewStyleDefault;
    [alert show];
}

#pragma mark -
#pragma mark backButtonEvent

- (void)backButtonEvent:(id)sender
{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

@end
